package com.example.demo.thread;

import org.junit.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ThreeThread {

    @Test
    public void printTest() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        // 打印a线程的condition
        Condition conditionA = lock.newCondition();
        // 打印b线程的condition
        Condition conditionB = lock.newCondition();
        // 打印c线程的condition
        Condition conditionC = lock.newCondition();

        Thread printerA = new Thread(new Printer(lock, conditionA, conditionB, 'A'));
        Thread printerB = new Thread(new Printer(lock, conditionB, conditionC, 'B'));
        Thread printerC = new Thread(new Printer(lock, conditionC, conditionA, 'C'));

        // 依次开始A B C线程
        printerA.start();
        Thread.sleep(100);
        printerB.start();
        Thread.sleep(100);
        printerC.start();

        Thread.sleep(50000);
    }

    public static class Printer implements Runnable {

        // 打印次数
        private static final int PRINT_COUNT = 10;
        // 打印锁
        private final ReentrantLock reentrantLock;
        // 本线程打印所需的condition
        private final Condition thisCondition;
        // 下一个线程打印所需要的condition
        private final Condition nextCondition;
        // 打印的字符
        private final char printChar;

        public Printer(ReentrantLock reentrantLock, Condition thisCondition, Condition nextCondition, char printChar) {
            this.reentrantLock = reentrantLock;
            this.thisCondition = thisCondition;
            this.nextCondition = nextCondition;
            this.printChar = printChar;
        }

        @Override
        public void run() {
            reentrantLock.lock();
            try {
                for (int i = 0; i < PRINT_COUNT; i++) {
                    System.out.println(printChar);
                    nextCondition.signal();
                    if (i < PRINT_COUNT - 1) {
                        try {
                            // 本线程让出锁并等待唤醒
                            thisCondition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } finally {
                reentrantLock.unlock();
            }
        }
    }
}
